import 'package:flutter/material.dart';
import '../servers/api_service.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../services/constants.dart';
import '../services/market_events.dart';
import '../services/token_manager.dart';

class GoodsDetailPage extends StatefulWidget {
  final Map<String, dynamic> goods;
  const GoodsDetailPage({super.key, required this.goods});

  @override
  State<GoodsDetailPage> createState() => _GoodsDetailPageState();
}

class _GoodsDetailPageState extends State<GoodsDetailPage> {
  final PageController _pageController = PageController();
  int _currentImageIndex = 0;
  String _sellerAvatar = '';
  String _sellerNickname = '';
  String _sellerEmail = '';
  bool _avatarFetchStarted = false;

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _loadLocalAvatar();
  }

  Future<void> _loadLocalAvatar() async {
    try {
      final info = await TokenManager.instance.getUserInfo();
      final localAvatar = (info['avatar'] ?? '')?.toString() ?? '';
      if (mounted && localAvatar.isNotEmpty) {
        setState(() {
          _sellerAvatar = localAvatar;
        });
      }
    } catch (_) {}
  }

  Future<void> _fetchSellerAvatarOnce() async {
    if (_avatarFetchStarted || _sellerEmail.isEmpty || _sellerAvatar.isNotEmpty) return;
    _avatarFetchStarted = true;
    try {
      final res = await ApiService().getUserAvatar(_sellerEmail);
      final remoteAvatar = (res != null) ? (res['avatar'] ?? res['data']?['avatar']) : null;
      if (mounted && remoteAvatar is String && remoteAvatar.isNotEmpty) {
        setState(() {
          _sellerAvatar = remoteAvatar;
        });
      }
    } catch (_) {}
  }

  List<String> get _images {
    final raw = widget.goods['images'];
    if (raw is String && raw.isNotEmpty) {
      return raw.split(',').where((e) => e.trim().isNotEmpty).toList();
    }
    if (raw is List) {
      return raw.cast<String>();
    }
    return const [];
  }

  @override
  Widget build(BuildContext context) {
    final name = (widget.goods['name'] ?? '').toString();
    final price = (widget.goods['price'] ?? '').toString();
    final address = (widget.goods['address'] ?? '').toString();
    final goodsDesc = (widget.goods['goodsDesc'] ?? '').toString();

    // 初始化卖家信息（一次性）
    _sellerNickname = _sellerNickname.isNotEmpty
        ? _sellerNickname
        : ((widget.goods['seller']?['username'] ?? widget.goods['userEmail'] ?? '').toString());
    _sellerAvatar = _sellerAvatar.isNotEmpty
        ? _sellerAvatar
        : ((widget.goods['seller']?['avatar'] ?? '').toString());
    _sellerEmail = _sellerEmail.isNotEmpty
        ? _sellerEmail
        : ((widget.goods['seller']?['email'] ?? widget.goods['userEmail'] ?? '').toString());

    // 若无头像但有邮箱，尝试拉取头像（只触发一次）
    if (_sellerAvatar.isEmpty && _sellerEmail.isNotEmpty) {
      _fetchSellerAvatarOnce();
    }

    return Scaffold(
      appBar: AppBar(title: const Text('商品详情')),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              children: [
                Container(
                  color: Colors.white,
                  padding: const EdgeInsets.all(15),
                  child: Row(
                    children: [
                      CircleAvatar(
                        radius: 24,
                        backgroundColor: Colors.grey[300],
                        backgroundImage: _sellerAvatar.isNotEmpty ? NetworkImage(_sellerAvatar) : null,
                        child: _sellerAvatar.isEmpty
                            ? Icon(
                                Icons.person,
                                size: 28,
                                color: Colors.grey[600],
                              )
                            : null,
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              _sellerNickname.isEmpty ? '卖家' : _sellerNickname,
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              name,
                              style: const TextStyle(
                                fontSize: 16,
                                color: Colors.black87,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 10),
                Container(
                  color: Colors.white,
                  padding: const EdgeInsets.all(15),
                  child: Text(
                    '¥' + price,
                    style: TextStyle(
                      color: Colors.red[700],
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                const SizedBox(height: 10),
                Container(
                  color: Colors.white,
                  padding: const EdgeInsets.all(15),
                  child: _buildInfoRow(Icons.location_on_outlined, '位置', address),
                ),
                const SizedBox(height: 10),
                Container(
                  color: Colors.white,
                  padding: const EdgeInsets.all(15),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '商品描述',
                        style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 10),
                      Text(
                        goodsDesc.isEmpty ? '无' : goodsDesc,
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[700],
                          height: 1.5,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 10),
                _buildImageCarousel(),
                const SizedBox(height: 80),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 10,
                  offset: const Offset(0, -2),
                ),
              ],
            ),
            child: SafeArea(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                child: Row(
                  children: [
                    Expanded(
                      child: FilledButton(
                        onPressed: () {
                          _showSubmitOrderSheet();
                        },
                        style: FilledButton.styleFrom(
                          padding: const EdgeInsets.symmetric(vertical: 14),
                        ),
                        child: const Text('立即购买', style: TextStyle(fontSize: 16)),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageCarousel() {
    final images = _images;
    return Container(
      color: Colors.grey[200],
      height: 375,
      child: Stack(
        children: [
          PageView.builder(
            controller: _pageController,
            itemCount: images.isEmpty ? 1 : images.length,
            onPageChanged: (index) {
              setState(() {
                _currentImageIndex = index;
              });
            },
            itemBuilder: (context, index) {
              if (images.isEmpty) {
                return Container(
                  color: Colors.grey[300],
                  child: Icon(
                    Icons.image_outlined,
                    size: 80,
                    color: Colors.grey[400],
                  ),
                );
              } else {
                return Image.network(
                  images[index],
                  fit: BoxFit.cover,
                  width: double.infinity,
                );
              }
            },
          ),
          if (images.length > 1)
            Positioned(
              right: 15,
              bottom: 15,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  (_currentImageIndex + 1).toString() + '/' + images.length.toString(),
                  style: const TextStyle(color: Colors.white, fontSize: 12),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildInfoRow(IconData icon, String label, String value) {
    return Row(
      children: [
        Icon(icon, size: 20, color: Colors.grey[600]),
        const SizedBox(width: 8),
        Text(
          label,
          style: TextStyle(fontSize: 14, color: Colors.grey[600]),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            value,
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }

  void _showSubmitOrderSheet() {
    final nameCtrl = TextEditingController();
    final phoneCtrl = TextEditingController();
    final detailCtrl = TextEditingController(text: (widget.goods['address'] ?? '').toString());
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return Padding(
          padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
          child: Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('填写收货信息', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                const SizedBox(height: 12),
                TextField(controller: nameCtrl, decoration: const InputDecoration(labelText: '收货人')),
                TextField(controller: phoneCtrl, decoration: const InputDecoration(labelText: '手机号'), keyboardType: TextInputType.phone),
                TextField(controller: detailCtrl, decoration: const InputDecoration(labelText: '详细地址')),
                const SizedBox(height: 16),
                SizedBox(
                  width: double.infinity,
                  child: FilledButton(
                    onPressed: () async {
                      if (nameCtrl.text.isEmpty || phoneCtrl.text.isEmpty || detailCtrl.text.isEmpty) {
                        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('请完整填写收货信息')));
                        return;
                      }
                      Navigator.pop(context);
                      await _submitOrder(
                        addressName: nameCtrl.text,
                        addressPhone: phoneCtrl.text,
                        addressDetail: detailCtrl.text,
                      );
                    },
                    child: const Text('提交订单'),
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> _submitOrder({required String addressName, required String addressPhone, required String addressDetail}) async {
    try {
      final info = await TokenManager.instance.getUserInfo();
      final email = (info['email'] ?? '').toString();
      if (email.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('未登录，无法下单')));
        return;
      }
      final headers = {
        'Content-Type': 'application/json',
        'email': email,
      };
      final body = jsonEncode({
        'goodsId': widget.goods['id'],
        'addressName': addressName,
        'addressPhone': addressPhone,
        'addressDetail': addressDetail,
      });
      final url = Uri.parse('${Constants.serverUrl}order/submitOrder');
      final res = await http.post(url, headers: headers, body: body);
      if (!mounted) return;
      if (res.statusCode == 200) {
        final data = jsonDecode(res.body);
        if (data['code'] == 0) {
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('下单成功')));
          MarketEvents.instance.notifyChanged();
          return;
        }
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('下单失败: ${data['msg'] ?? '未知错误'}')));
      } else {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('下单失败: HTTP ${res.statusCode}')));
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('下单失败: $e')));
    }
  }
}


